<template>
    <div class="upload" v-loading="loading">
        <div class="upload_title">{{title}}</div>
        <el-upload
        class="upload-demo"
        :action="action"
        :on-preview="handlePreview"
        :on-remove="handleRemove"
        :before-remove="beforeRemove"
        :on-success="uploadSuccess"
        :multiple="true"
        :on-exceed="handleExceed"
        :file-list="fileList">
        <el-button size="small" type="primary" v-if="isreadonly!='Y'">点击上传</el-button>
        <div slot="tip" class="el-upload__tip"></div>
        </el-upload>

        <el-dialog :title="iframeTitle" width="90%" :visible.sync="outerVisible" append-to-body>
            <div style="height:80VH">
                <!--iframe :src="onlineUrl" frameborder="no" width="100%" height="100%"></iframe-->
               
                <el-image 
                    
                v-for="(item,index) in imgList" :key="index" width="100%" lazy-load :src="item.url" >
                </el-image>
            </div>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="downFile">下载</el-button>
                <el-button @click="outerVisible = false">确定</el-button>
            </div>
        </el-dialog>
        <el-dialog :title="iframeTitle" width="90%" :visible.sync="outerVisible2" append-to-body>
            <div style="height:80VH" class="imgView">
                <el-image 
                    
                    :src="onlineUrl" 
                    fit="fill"
                    :preview-src-list="onlineUrl.split(',')">
                </el-image>
            </div>
            
            <div slot="footer" class="dialog-footer">
                <el-button type="primary" @click="downFile">下载</el-button>
                <el-button @click="outerVisible2 = false">确定</el-button>
            </div>
        </el-dialog>
    </div>
    
</template>
<script>

export default {
    
  
    props:["id","data","title","exkey","isreadonly"],
    data(){
        return{
            action:"",
            fileList:[],
            pId:"",
            cId:"",
            model:"",
            type:"",
            fileType:"",
            fileKey:"",
            filePid:"",
            fileId:"",
            imageMap:{},
            sid:"",
            outerVisible:false,
            outerVisible2:false,
            onlineUrl:"",
            imgList:[],
            outlineUrl:"",
            onlineHtml:"",
            iframeTitle:"",
            loading:false
        }
    },
    created(){
        try{
            if(this.exkey&&this.exkey.model){
                this.model=this.exkey.model;
            }
            if(this.exkey&&this.exkey.type){
                this.type=this.exkey.type;
            }
            if(this.exkey&&this.exkey.fileType){
                this.fileType=this.exkey.fileType;
            }
            if(this.exkey&&this.exkey.id){
                this.fileKey=this.exkey.id;
                let ids=this.fileKey.split(".");
                this.filePid=ids[0];
                this.fileId=ids[1]
                this.sId=this.data[this.filePid][this.fileId]
                if(!this.sId){
                    this.sId=this.randomString(12);
                }
            }
        }catch(e){}
        this.action="/business/api/file/fileUpload?isVideo=Y&type="+this.type+"&model="+this.model+"&isPdf=Y&token="+sessionStorage.getItem("token")+"&id="+this.sId
        try{
            let ids=this.id.split(".");
            this.pId=ids[0];
            this.cId=ids[1]
        }catch(e){}
        if(this.fileType){
            this.imageMap={};
            this.$post("business","/api/file/getFile",{
                model:this.model,
                type:this.type,
                id:this.data[this.filePid][this.fileId]
            }).then(data=>{
                    
                this.fileList=[];
             
                let isOk=false;
                for(let i=0;i<data.length;i++){
                    if(data[i].url){
                        let data_={};
                        data_.url=data[i].url;
                        data_.name=data[i].name;
                        this.fileList.push(data_);
                       
                        this.imageMap[data[i].url]=data[i].id;
                        isOk=true;
                        
                    }
                    
                }
                try{
                    if(this.exkey.isAutoView=="Y"&&this.fileList.length>0){
                        
                        window.setTimeout(()=>{

                            let name=this.fileList[0].name;
                            let url=this.fileList[0].url
                            this.handleView(name,url)
                        },1000)
                    }
                }catch(e){}
                console.log(this.fileList,"this.fileList==========")
               
            })
        }else{
            if(this.data[this.pId][this.cId]){
                let fileLists=this.data[this.pId][this.cId].split(",");
                for(let i=0;i<fileLists.length;i++){
                    let f={};
                    f.url=fileLists[i];
                    f.name="文档"
                    this.fileList.push(f);
                }
                console.log(this.fileList,"fileList=====================")
            }
        }
        
        
    },
    methods:{
       
        randomString(len) {
            len = len || 32;
            var $chars = 'ABCDEFGHJKMNPQRSTWXYZabcdefhijkmnprstwxyz2345678';    /****默认去掉了容易混淆的字符oOLl,9gq,Vv,Uu,I1****/
            var maxPos = $chars.length;
            var pwd = '';
            for (let i = 0; i < len; i++) {
                pwd += $chars.charAt(Math.floor(Math.random() * maxPos));
            }
            return pwd;
        },
         handleRemove(file, fileList) {
            console.log(file, fileList);
            console.log(file.response)

            console.log("url=========="+file.url)
            let url=file.url
            if(this.fileType){
                
                let ids=this.imageMap[url];
                let datas=this.data["imageList_"];
                if(!datas){
                    datas=[];
                }
                let index=-1;
                for(let i=0;i<datas.length;i++){
                    let data_=datas[i];
                    if(data_.model==this.model&&data_.type==this.type){
                        index=i;
                    }
                }
                
                if(index==-1){
                    index=datas.length;
                    let data_={};
                    data_.model=this.model;
                    data_.type=this.type;
                    data_.sId=this.sId;
                    data_.del_id=ids;
                    data_.id="";
                    data_.key=this.fileId;
                    data_.keyPid=this.filePid;
                    datas.push(data_);
                    this.$set(this.data,"imageList_",datas)
                }else{
                    let data_=datas[index];
                    let id=data_["del_id"];
                    id=id=="" ? ids:id+","+ids;
                    datas[index].del_id=id;
                    this.$set(this.data,"imageList_",datas)
                }
            }else{
                let urls=this.data[this.pId][this.cId]
                for(let i=0;i<file.response.length;i++){
                    let url=file.response[0].url;
                    urls=urls.replace(","+url+",","");
                    urls=urls.replace(","+url,"");
                    urls=urls.replace(url+",","");
                    urls=urls.replace(url,"");
                }
                this.data[this.pId][this.cId]=urls;
                console.log("urls==="+urls);

            }
            
        },
        handleView(name,url){
            this.iframeTitle=name;
            
            this.outlineUrl=url;
            if(name.toUpperCase().indexOf(".DOC")!=-1||name.toUpperCase().indexOf(".PDF")!=-1||name.toUpperCase().indexOf(".XLS")!=-1){
                this.loading=true;
                //http://view.xdocin.com/xdoc?_xdoc=
                
                //let urls="http://view.xdocin.com/xdoc?_xdoc=http://8.136.193.200/"+url;
                let urls="";
                this.$post("business","api/view/pdfView",{url:url}).then(data=>{
                    if(data.status=="200"){
                        this.imgList=data.url;
                        this.outerVisible=true;
                    }
                    this.loading=false;
                })
                /*this.$fetch3(urls).then(data=>{
                    console.log(data)
                    this.onlineHtml=data;
                })*/

                //this.onlineUrl=urls;
               
                /*this.$nextTick(function(){
                    //const oIframe = document.getElementById('show-iframe');
                    console.log(this.$refs.onlineIframe,"el===")
                    console.log(this.$refs.onlineIframe.$el,"el===")
                    let that=this;
                    window.setTimeout(function(){
                        console.log(that.$refs.onlineIframe.$el,"el2===")
                       
                    },2000)
                  
                   
                   
                });*/
              
            }else if(name.toUpperCase().indexOf(".PNG")!=-1||name.toUpperCase().indexOf(".JPG")!=-1||name.toUpperCase().indexOf(".JPEG")!=-1){
                
                this.outerVisible2=true;
                this.onlineUrl=url;
            }else{
                this.$confirm('暂不支持在线预览, 是否下载?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                    }).then(() => {
                        this.downFile();
                    }).catch(() => {
                         
                    });
            }
        },
        handlePreview(file) {
            let name="";
            let url="";
            if(file.response){
                console.log(file.response[0]);
                url=file.response[0].url;
                name=file.response[0].name;
            }else{
                console.log(file)
                url=file.url;
                name=file.name;
            }
            this.handleView(name,url)
            
        },
        handleExceed(files, fileList) {
            this.$message.warning(`当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        },
        beforeRemove(file, fileList) {

            return this.$confirm(`确定移除 ${ file.name }？`);
        },
        uploadSuccess(response, file, fileList){
           console.log(response);
           let ids="";
            for(let i=0;i<response.length;i++){
                this.imageMap[response[i].url]=response[i].f_id
                ids=ids=="" ? response[i].f_id:ids+","+f_id;
            }
           if(this.fileType){
                let datas=this.data["imageList_"];
                if(!datas){
                    datas=[];
                }
                let index=-1;
                for(let i=0;i<datas.length;i++){
                    let data_=datas[i];
                    if(data_.model==this.model&&data_.type==this.type){
                        index=i;
                    }
                }
                
                if(index==-1){
                    index=datas.length;
                    let data_={};
                    data_.model=this.model;
                    data_.type=this.type;
                    data_.id=ids;
                    data_.sId=this.sId;
                    data_.key=this.fileId;
                    data_.keyPid=this.filePid;
                    data_.del_id="";
                    datas.push(data_);
                    this.$set(this.data,"imageList_",datas)
                }else{
                    let data_=datas[index];
                    let id=data_["id"];
                    id=id=="" ? ids:id+","+ids;
                    datas[index].id=id;
                    this.$set(this.data,"imageList_",datas)
                }
           }else{
                let urls=this.data[this.pId][this.cId];
                for(let i=0;i<response.length;i++){
                    let url=response[0].url;
                    urls=urls=="" ? url:urls+","+url;
                }
                this.data[this.pId][this.cId]=urls;
           }
          
           // console.log("urls==="+urls);
           // console.log(this.fileList)
        },
        downFile(){
           
            let a = document.createElement("a");
            a.href ='/business/api/file/downFile?path='+this.outlineUrl.replace("/business/image/","")+"&token="+sessionStorage.getItem("token");
            document.body.appendChild(a);
            a.click();  //下载
            URL.revokeObjectURL(a.href);    // 释放URL 对象 
            document.body.removeChild(a);   // 删除 a 标签
        }
    }
}
</script>
<style scoped>
    .upload{
        width:100%;
        text-align:center;
    }
    .upload-demo>>>.el-upload-list__item{
        text-align:left;

    }
   .imgView{
    display:flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
   }
</style>